package com.education.teach.mvp.presenter;

import android.app.Application;

import com.education.teach.mvp.model.bean.LoginBean;
import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;

import dn.easy.common.commonutils.StringUtils;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import okhttp3.ResponseBody;

import javax.inject.Inject;

import com.education.teach.mvp.contract.LoginContract;
import com.jess.arms.utils.RxLifecycleUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@ActivityScope
public class LoginPresenter extends BasePresenter<LoginContract.Model, LoginContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    @Inject
    public LoginPresenter(LoginContract.Model model, LoginContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    public void login(String userName, String password) {
        if (StringUtils.isEmpty(userName)) {
            mRootView.showMessage("请输入用户名!");
            return;
        }
        if (StringUtils.isEmpty(password)) {
            mRootView.showMessage("请输入密码!");
            return;
        }
        Map<String, String> map = new HashMap<>();
        map.put("yhbm", userName);
        map.put("yhmm", password);
        mModel.login(map).
                subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .doOnSubscribe(disposable -> mRootView.showLoading())
                .doFinally(() -> mRootView.hideLoading())
                .subscribe(new ErrorHandleSubscriber<LoginBean>(mErrorHandler) {
                    @Override
                    public void onNext(LoginBean loginBean) {
                        mRootView.returnLoginResult(loginBean);
                    }

                });
    }
}
